package com.victorvieux.android.web;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.victorvieux.android.handlers.PlaylistHandler;
import com.victorvieux.android.handlers.StatusHandler;


public class Communicate {
	private String request;
	private static Communicate _this = null;
	
	private Communicate () {
	}
	
	static public Communicate getInstance() {
		if (_this == null)
			_this = new Communicate();
		return (_this);
	}

	public void init(String ip, String port) {
		request = new String("http://" + ip + ":" + port + "/requests/");
	}
	
	public StatusHandler send(String command, int id) {
		String uurl = new String (request + "status.xml");
		if (command != null) {
			uurl += "?command=" + command;
			if (id != 0)
				uurl += "&id=" + id;
		}
		StatusHandler sh = new StatusHandler();
		SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
		try {
			URL url = new URL(uurl);
			url.openConnection();
			sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			xr.setContentHandler(sh);
			xr.parse(new InputSource(url.openStream()));
		} catch (ParserConfigurationException e) {return null;}
		catch (SAXException e) {return null;}
		catch (MalformedURLException e) {return null;} 
		catch (IOException e) {return null;}
        return (sh);
	}
	
  	public StatusHandler readStatus() {
        return (send(null, 0));
	}
	
	public PlaylistHandler readPlaylist() {
		PlaylistHandler ph = new PlaylistHandler();
		SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
		try {
			URL url = new URL(request + "playlist.xml");
			sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			xr.setContentHandler(ph);
			xr.parse(new InputSource(url.openStream()));
		} catch (ParserConfigurationException e) {return null;}
		catch (SAXException e) {return null;}
		catch (MalformedURLException e) {return null;}
		catch (IOException e) {return null;}
        return (ph);
	}
}
